package com.qgs.waf.util;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.net.URL;
import java.util.logging.Logger;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.jedis.JedisConnection;

import com.qgs.waf.service.RedisService;

/**
 * @show 将src目录下所有LUA脚本初始化
 * @show 将所有LUA初始化至Redis HASH中,KEY为script,field为脚本的文件名称,value为HASH码
 * @author Administrator
 *
 */
public class JedisLuaLoader extends Thread {

	@Autowired
	private RedisService rs;
	private static final Logger LOG = Logger.getLogger(JedisLuaLoader.class.toString());

	@Override
	public void run() {
		JedisConnection jc = rs.getJedisClient();
		super.run();
		URL lua_floder_url = Thread.currentThread().getContextClassLoader().getResource("lua");
		File lua_floder = new File(lua_floder_url.getFile());
		// 当目录为文件夹的时候加载脚本
		if (lua_floder.isDirectory()) {
			File[] fs = lua_floder.listFiles();
			for (File file : fs) {
				LOG.info("scriptLoad:" + file.getName());
				try {
					// 将所有LUA初始化至Redis
					// HASH中,KEY为script,field为脚本的文件名称,value为HASH码
					jc.hSet("script".getBytes(), file.getName().substring(0, file.getName().indexOf(".")).getBytes(), scriptLoad(jc, file2String(file)).getBytes());
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			jc.save();
		}
	}

	public static String file2String(File file) throws IOException {
		BufferedReader br = new BufferedReader(new FileReader(file));
		StringBuffer sb = new StringBuffer();
		String line;
		while ((line = br.readLine()) != null) {
			sb.append(line);
		}
		br.close();
		return sb.toString();
	}

	public static String scriptLoad(JedisConnection jc, String script) {
		return jc.scriptLoad(script.getBytes());
	}
}
